from config import *
import json
import os


def update_cookie(cookies:str=None, url=r'https://zhuanlan.zhihu.com/p/622364619'):
    if not cookies:
        # selenium 未必可以拿到正确的 cookies，该分支暂且无用
        try:
            from selenium import webdriver
        except ImportError:
            import sys
            sys.stderr.write('若要自动从浏览器获取cookie，请自行安装 selenium 库。')
            sys.exit(-1)
        try:
            driver = webdriver.Chrome()
        except:
            driver = webdriver.Edge()
        if os.path.exists(STEALTH_JS_PATH):
            with open(STEALTH_JS_PATH, 'r') as f:
                js = f.read()
                driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': js})
        else:
            # TODO: 自动下载
            import sys
            sys.stderr.write(f'请从 https://github.com/requireCool/stealth.min.js 下载 stealth.min.js 并置于 {os.path.dirname(STEALTH_JS_PATH)} 目录下')
            sys.exit(-1)
        driver.get(url)
        cookies = driver.get_cookies()
        driver.close()

    if isinstance(cookies, str):
        d = {}
        for c in cookies.split('; '):
            k, v = c.split('=', 1)
            d[k] = v
        cookies = d
    else:
        cookies = {d['name']: d['value'] for d in cookies}
    with open(COOKIE_PATH, 'w', encoding='utf-8') as f:
        f.write(json.dumps(cookies))


if __name__ == '__main__':
    update_cookie()